package com.heartbridge.base64;

import com.github.heartbridge.fs.annotation.Handler;
import com.github.heartbridge.fs.annotation.RequestMapping;
import com.github.heartbridge.fs.annotation.RequestParam;
import com.github.heartbridge.fs.server.ServerStartParamsAware;
import com.github.heartbridge.fs.utils.FileUtils;
import com.github.heartbridge.fs.utils.Images;
import com.github.heartbridge.fs.utils.Maps;
import com.github.heartbridge.fs.utils.TypeConvertor;
import com.github.heartbridge.fs.utils.WebResponse;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @author GavinCook
 * @since 1.0.0
 **/
@Handler
public class Base64ImageHandler implements ServerStartParamsAware {

    private Logger logger = Logger.getLogger(getClass().getName());

    private String baseDir;

    private int threshold;

    @RequestMapping(value = "/base64")
    public WebResponse processBase64Image(@RequestParam("content")String[] content,
                                          @RequestParam(value = "avatar",defaultValue = "false") Boolean isAvatar){

        if (content != null && content.length > 0){
            int baseDirLength = baseDir.length()-1;
            List<Map<String,Object>> success = new ArrayList<>();
            List<Map<String,Object>> failure = new ArrayList<>();
            BASE64Decoder decoder = new BASE64Decoder();
            File out;
            for(String imgStr : content) {
                int dotPosition = imgStr.indexOf(",");
                if(dotPosition != -1){//去除前面格式为：data:image/jpg;base64,的数据
                    imgStr = imgStr.substring(dotPosition+1);
                }
                try {
                    //Base64解码
                    byte[] data = decoder.decodeBuffer(imgStr);
                    for (int i = 0; i < data.length; ++i) {
                        if (data[i] < 0) {//调整异常数据
                            data[i] += 256;
                        }
                    }
                    File f = new File(FileUtils.getTimestampPath(baseDir),System.currentTimeMillis()+".jpg");
                    out = FileUtils.getFileNotExists(f);
                    FileUtils.createIfNotExists(out.getAbsolutePath(), false);

                    File originImageFile = FileUtils.createIfNotExists(out.getParent()+File.separator+"origin_"+out.getName(), false);
                    FileUtils.save(data,originImageFile);//保存原图,原图直接保存，避免imageIO读取后变红

                    BufferedImage originImage = ImageIO.read(new ByteArrayInputStream(data));
                    float quality = 1.0f;
                    if(content.length>threshold){//大于1m才压缩
                        quality = 0.8f;
                        originImage = Images.compressImage(originImage, quality);//压缩
                    }

                    if(isAvatar){//如果是头像需要保存一个200*200的尺寸，并且将200*200设为默认
                        originImage = Images.toSquare(originImage);//正方形
                        BufferedImage image200 = Images.scaleImage(originImage,200,200,true,false);
                        ImageIO.write(image200,"jpg",out);
                        BufferedImage image100 = Images.scaleImage(originImage,100,100,true,false);
                        ImageIO.write(image100,"jpg",new File(out.getParentFile(),"100_"+out.getName()));
                    }else{
                        BufferedImage image100 = Images.scaleImage(originImage,100,100,true,false);
                        ImageIO.write(image100,"jpg",out);
                    }

                    success.add(Maps.mapItSO(
                            "fileName", out.getName(),
                            "filePath", out.getAbsolutePath().substring(baseDirLength).replaceAll("\\\\", "/")));
                } catch (Exception e) {
                    failure.add(Maps.mapItSO(
                            "errorMsg", e.getMessage()));
                    e.printStackTrace();
                }
            }
            return WebResponse.success(Maps.mapItSO("success",success,"failure",failure));
        }
        return  WebResponse.success(Maps.mapItSO("success", new String[0], "failure", new String[0]));
    }

    @Override
    public void setStartParams(Map<String, String> map) {
        this.baseDir = map.get(ServerStartParamsAware.BASEDIR);
        this.threshold = TypeConvertor.toInteger(map.get(ServerStartParamsAware.THRESHOLD));
    }
}
